<template>
  <div class="home-page">
    <section class="py-5 text-center container">
      <div class="row py-lg-5">
        <div class="col-lg-6 col-md-8 mx-auto">
          <img src="../assets/callout.svg" alt="callout" class="w-50" />
          <h2 class="font-weight-light">随心写作，自由表达</h2>
          <p>
            <router-link to="/create"
              ><a href="#" class="btn btn-primary my-2"
                >开始写文章</a
              ></router-link
            >
          </p>
        </div>
      </div>
    </section>

    <h4 class="font-weight-bold text-center">发现精彩</h4>
    <column-list :list="list"></column-list>
    <!-- <button
      class="btn btn-outline-primary mt-2 mb-5 mx-auto w-25"
      style="display:block"
      @click="loadMorePage"
      v-if="!isLastPage"
    >
      加载更多
    </button> -->
    <span ref="loadMoreRef" style="display:block"></span>
  </div>
</template>

<script lang="ts">
import { ref, computed, defineComponent, onMounted } from "vue";
import { useStore } from "vuex";
import { GlobalDataProps } from "@/store";
import useLoadMore from "../hooks/useLoadMore";
import ColumnList from "../components/ColumnList.vue";

export default defineComponent({
  name: "Home",
  components: {
    ColumnList
  },
  setup() {
    const store = useStore<GlobalDataProps>();
    let list = computed(() =>
      // 首页渲染的专栏数据应该里面有个字段feature
      store.getters.getColumns.filter((c: any) => c.featured === true)
    );
    const total = computed(() => store.state.columns.total);
    const currentPage = computed(() => store.state.columns.currentPage);

    // 增加useloadmore功能
    // const { loadMorePage, isLastPage } = useLoadMore("fetchColumns", total, {
    //   pageSize: 3,
    //   // 如果currentPage===0的时候 加载第二页，如果currentPage有值的话就加载下一页
    //   currentPage: currentPage.value ? currentPage.value + 1 : 2
    // });

    const options = {
      root: null,
      rootMargin: "80px 0px 80px 0px",
      threshold: [0.3]
    };
    const { loadMorePage, isLastPage } = useLoadMore("fetchColumns", total, {
      pageSize: 3,
      currentPage: currentPage.value ? currentPage.value + 1 : 2
    });
    const io = new IntersectionObserver(
      (entries: IntersectionObserverEntry[]) => {
        entries.forEach((entry: IntersectionObserverEntry) => {
          if (entry.isIntersecting) {
            loadMorePage();
            if (isLastPage.value) {
              loadMoreRef.value && io.unobserve(loadMoreRef.value);
            }
          }
        });
      },
      options
    );
    const loadMoreRef = ref<HTMLElement | null>(null);
    // 注意 onMount之后才能监听
    onMounted(() => {
      // 发起请求
      store.dispatch("fetchColumns", { pageSize: 3 }).then(() => {
        list = computed(() => store.state.columns);
      });
      loadMoreRef.value && io.observe(loadMoreRef.value);
    });

    return {
      list,
      loadMorePage,
      isLastPage,
      loadMoreRef
    };
  }
});
</script>
